import { useJackpotStore } from '@/store'
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/login.vue'),
        meta: {
            title: '登录'
        }
    },
    {
        path: '/register',
        name: 'Register',
        component: () => import('@/views/register.vue'),
        meta: {
            title: '注册'
        }
    },
    {
        path: '/index',
        name: 'Index',
        component: () => import('@/views/client.vue'),
        meta: {
            title: '首页'
        }
    },
    {
        path: '/',
        name: 'Layout',
        redirect: '/userInfo',
        component: () => import('@/layout/index.vue'),
        meta: {
            title: '首页'
        },
        children: [
            {
                path: 'userInfo',
                name: 'UserInfo',
                component: () => import('@/views/user-info.vue'),
                meta: {
                    title: '用户信息'
                }
            },
            {
                path: 'jackpot',
                name: 'Jackpot',
                component: () => import('@/views/jackpot.vue'),
                meta: {
                    title: '游戏用户'
                }
            },
            {
                path: 'result',
                name: 'Result',
                component: () => import('@/views/result.vue'),
                meta: {
                    title: '游戏结果'
                }
            },
            {
                path: 'oddRule',
                name: 'OddRule',
                component: () => import('@/views/odd-rule.vue'),
                meta: {
                    title: '游戏规则'
                }
            },
            {
                path: 'waterDict',
                name: 'WaterDict',
                component: () => import('@/views/water/dict.vue'),
                meta: {
                    title: '水票字典'
                }
            },
            {
                path: 'waterOrder',
                name: 'WaterOrder',
                component: () => import('@/views/water/order.vue'),
                meta: {
                    title: '水票订单'
                }
            }
        ]
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('@/views/404.vue')
    }
]

const router = createRouter({
    history: createWebHistory(import.meta.env.VITE_BUILD_PATH),
    routes
})

// @ts-ignore
router.beforeEach((to, from, next) => {
    const whileList = ['/login', '/register']
    const token = useJackpotStore().token
    if (token) {
        if (whileList.includes(to.path)) {
            next('/')
        } else {
            next()
        }
    } else {
        if (whileList.includes(to.path)) {
            next()
        } else {
            next('/login')
        }
    }
})

export default router
